#include "./jumper.h"

Sky::NType::Bool JumperApp::init(int x,int y,int w,int h)
{
	myApplet::init();

	Handler::Delegate handle(this,&JumperApp::OnTimer);

	getEventMgr().createTimer(handle,1);

	_win.init(&getResMgr(),x,y,w,h);

	getWindowMgr().attachFirst(&_win);


	return vTrue;
}

Sky::NValue::MsgStatus JumperApp::OnTimer( myMsgMgr* mgr,Msg* msg )
{
	mgr->getApplication()->getTimeCounter().CalTicksElapsed();

	_win.updateTime(&mgr->getApplication()->getTimeCounter());
	myWinMsg msg2(&myWinlet::handlePaint,getPainter(),getPainter());


	return getWindowMgr().handleDrawEvent(&getEventMgr(),&msg2);
}


Sky::NType::Bool JumperWin::init( myResMgr* mgr,i32 x,i32 y,i32 w,i32 h )
{
	_man.init(mgr);
	_man.setRect(0,0,10,10);
	for(int i = -20; i < 20; i ++)
	{
		Trigger* trigger = new Trigger(PointF(i * 20,200 * ((i + 20)%2) - 100),20,(Trigger*)getFirstChild(),1000.0f);
		trigger->setVisible(vTrue);
		attachFirstChild(trigger);
	}
	Trigger* first = (Trigger*)getFirstChild();
	Trigger* last = (Trigger*)getLastChild();
	last->setNextTrigger(first);


	_man.setSpeed(Vector2F(0,-20));
	_man.setTarget(first->getPositionF());
	myWinlet::init(mgr,x,y,w,h);

	return vTrue;
}

Sky::MsgStatus JumperWin::onPaint( myMsgMgr* mgr,Msg* msg )
{

	Sky::Painter* painter = Sky::Painter::castFrom(msg->getMessage());
	
	Draw(painter);

	_man.Draw(painter);

	return vIntercepted;
}

Sky::MsgStatus JumperWin::onInput( myMsgMgr* mgr,Msg* msg )
{
	
	return vContinue;
}

Sky::NType::Void JumperWin::updateTime( TimeCounter* tc )
{
	Trigger* t = (Trigger*)getFirstChild();
	while(t)
	{
		if(t->adjust(&_man))
			break;
		t = (Trigger*)t->getNextSibling();
		if(t == getFirstChild())
			break;
	}
	_man.updateTime(tc);
}

JumperWin::~JumperWin()
{
	TreeNode* n = detachLastChild();
	while(n)
	{
		delete n;
		n = detachLastChild();
	}
}

Sky::NType::Void JumpMan::init( myResMgr* resManager,PointF pos,Vector2F speed,Vector2F direction )
{

}

Sky::NType::Void JumpMan::updateTime( TimeCounter* ct )
{
	_pos.x += ct->getElapsedTime() * _speed.x;
	_pos.y += ct->getElapsedTime() * _speed.y;

	return ;
}

Sky::NType::Void JumpMan::Draw( Painter* painter,Rect* parentRect )
{
	Rect r((i32)_pos.x,(i32)_pos.y,getRect()->w,getRect()->h);
	painter->fillRect(r,Color(255,0,0));
	return;
}

Trigger::Trigger( PointF pos,Float radis,Trigger* next,Float speed )
{
	_pos = pos;
	_radis = radis;
	_trigger = next;
	_speed = speed;
}

Sky::NType::Void Trigger::Draw( Painter* painter,Rect* parentRect /* = vNull */ )
{
	painter->fillRect(Rect((i32)_pos.x,(i32)_pos.y,5,5),Color(255,0,255));
}

Sky::NType::Bool Trigger::adjust( JumpMan* man )
{
	PointF pos = man->getPositionF();
	Float dist = Helper::distance(pos,_pos);
	if(dist < _radis && _trigger)
	{
		man->adjust(_trigger->getPositionF(),_speed);
		return vTrue;
	}
	return vFalse;
}
